# -*- coding: utf-8 -*-
# Create your views here.
from wikicamp.documentation.models import Document,Tag,Categories
from wikicamp.documentation.forms import DocumentForm,CategoriesForm,TagForm,SearchForm,GroupForm
from django.shortcuts import render_to_response,get_object_or_404
from django.http import HttpResponseRedirect,HttpResponse
from django.template import RequestContext
from django.conf import Settings,settings
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.forms import AuthenticationForm,UserChangeForm,PasswordChangeForm
from django.contrib.auth.models import User,Permission,Group
from django.utils.encoding import smart_str,smart_unicode
from django.contrib.auth.decorators import *
import time

import os,subprocess,sys
import datetime
import locale
import string

def index(request):
    return HttpResponseRedirect("/documentation/categories/")

def documentation_logout(request):
    logout(request)
    return HttpResponseRedirect("/documentation/categories/")

def documentation_login(request):
    form = AuthenticationForm()
    return render_to_response('documentation/accounts.html', {'authform': form},context_instance=RequestContext(request))

def documentation_auth(request):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect("/documentation/categories/")
        else:
            xmsg = u"Kullanıcı Aktif Değil"
            form = AuthenticationForm()
            return render_to_response('documentation/accounts.html', {'authform': form,'xmsg':xmsg},context_instance=RequestContext(request))

    else:
        form = AuthenticationForm()
        form['username'].field.initial=request.POST['username'] 
        xmsg = u"Kullanıcı Adı veya Şifre Hatalı"
        return render_to_response('documentation/accounts.html', {'authform': form,'xmsg':xmsg},context_instance=RequestContext(request))

def documentation_auth_edit(request,user_name):
    
    xusername= request.user.username
    
    if not request.user.has_perm('documentation.change_users') and xusername!=user_name:
        return HttpResponseRedirect("/documentation/accounts/profile/"+ xusername +"/edit/")
    else:
        usr = User.objects.get(username=user_name)
    
    form = UserChangeForm(instance=usr)
    form['user_permissions'].field.queryset = form['user_permissions'].field.queryset.filter(content_type=settings.DOCUMENTATION_PERM_ID)
    xlast_login = usr.last_login
    xdate_joined = usr.date_joined
    xis_superuser = usr.is_superuser
    xis_staff = usr.is_staff
    
    if request.user.has_perm('documentation.change_users'):
        usrlist = User.objects.all().exclude(is_superuser=1)
    else:
        usrlist =[]
    
    return render_to_response('documentation/accounts.html', {'authformedit': form,'usr':usr,'xusername':user_name,'xdate_joined':xdate_joined,'xlast_login':xlast_login,'xis_superuser':xis_superuser,'xis_staff':xis_staff,'usrlist':usrlist},context_instance=RequestContext(request))
    
def documentation_auth_save(request,user_name):
    usrinstance = get_object_or_404(User,username=user_name)
    perms =[]
    
    for px in usrinstance.user_permissions.all():
        perms.append(px.id)
       
    
    aktarilacak_perms = Permission.objects.filter(id__in=perms).exclude(content_type=settings.DOCUMENTATION_PERM_ID)
    
  
    if request.method == 'POST':
        
        form = UserChangeForm(data=request.POST,  instance=usrinstance)
        if form.is_valid():

            try:
                            
                form.save()
                usrinstance = User.objects.get(username=user_name)
               
                for p in aktarilacak_perms:
                    
                    usrinstance.user_permissions.add(p)
                
                usrinstance.save()
                return HttpResponseRedirect("/documentation/accounts/profile/"+ user_name +"/edit/")
            
            except Exception, e:
                    return HttpResponse("Hata : " + str(e))
        
        else:
            
            return render_to_response('documentation/accounts.html', {'authformedit': form,'usr':usr,'xusername':user_name},context_instance=RequestContext(request))

def documentation_auth_pass_change(request,user_name):
    
    xusername= request.user.username
    
    if not request.user.has_perm('documentation.change_users') and xusername!=user_name:
        return HttpResponseRedirect("/documentation/accounts/profile/"+ xusername +"/edit/")
    else:        
        usr= get_object_or_404(User,username=user_name)
        
    passchangeform=PasswordChangeForm(usr)
    return render_to_response('documentation/accounts.html', {'passchangeform': passchangeform,'usr':usr,'xusername':user_name},context_instance=RequestContext(request))

def documentation_auth_pass_save(request,user_name):
    usr= get_object_or_404(User,username=user_name)
    
    if request.method == "POST":
        
        form=PasswordChangeForm(request.POST)
        
        if usr.check_password(request.POST["old_password"]):
            
            if request.POST["new_password1"]==request.POST["new_password2"]:
                    
                    usr.set_password(request.POST["new_password1"])
                    usr.save()
                    return HttpResponseRedirect("/documentation/accounts/profile/"+ user_name +"/edit/")
            else:
                
                xmsg= "Yeni şifrelerde tutarsızlık.."
                
        else:
                
            xmsg= "Şifreniz Yanlış.."
            
        
        return render_to_response('documentation/accounts.html', {'passchangeform': form,'usr':usr,'xusername':user_name,'xmsg':xmsg},context_instance=RequestContext(request))
    
    
            
        
#@user_passes_test(lambda u: u.is_staff)
@permission_required('documentation.change_users')
def documentation_auth_groups(request):
    grps = Group.objects.filter().order_by('name')
    form = GroupForm()
    return render_to_response('documentation/groups.html',{'grps':grps,'form':form},context_instance=RequestContext(request))

@permission_required('documentation.change_users')
def documentation_auth_group_add(request):
    if "name" in request.POST:
        xgrp = request.POST["name"]
        Group.objects.get_or_create(name=xgrp)
    
    grps = Group.objects.filter().order_by('name')
    form = GroupForm()
    return render_to_response('documentation/groups.html',{'grps':grps,'form':form},context_instance=RequestContext(request))

@permission_required('documentation.change_users')
def documentation_auth_group_edit(request,group_id):
    grpinstance= get_object_or_404(Group,id=group_id)
    grpform = GroupForm(instance=grpinstance)
    grpform['permissions'].field.queryset = grpform['permissions'].field.queryset.filter(content_type=settings.DOCUMENTATION_PERM_ID)
    return render_to_response('documentation/groups.html',{'grpinstance':grpinstance,'grpform':grpform},context_instance=RequestContext(request))

@permission_required('documentation.change_users')
def documentation_auth_group_save(request,group_id):
    grpinstance = get_object_or_404(Group,id=group_id)
    perms =[]
    
    for px in grpinstance.permissions.all():
        perms.append(px.id)
       
    aktarilacak_perms = Permission.objects.filter(id__in=perms).exclude(content_type=settings.DOCUMENTATION_PERM_ID)
   
    if request.method == 'POST':
        
        form = GroupForm(data=request.POST,instance=grpinstance)
        if form.is_valid():

            try:
                            
                form.save()
                grpinstance = Group.objects.get(id=group_id)
               
                for p in aktarilacak_perms:
                    
                    grpinstance.permissions.add(p)
                
                grpinstance.save()
                return HttpResponseRedirect("/documentation/accounts/groups/"+ group_id +"/edit/")
            
            except Exception, e:
                    return HttpResponse("Hata : " + str(e))
        
        else:
            
            return render_to_response('documentation/groups.html',{'grpinstance':grpinstance,'grpform':form},context_instance=RequestContext(request))

@permission_required('documentation.change_users')
def documentation_auth_group_delete(request,group_id):
    try:
        grp = Group.objects.filter(id=group_id)
    except:
        return HttpResponseRedirect("/documentation/accounts/groups/")
        
    return render_to_response('documentation/groups.html', {'grpdeleteform': True,'group_id':group_id,'grp':grp,},context_instance=RequestContext(request))

@permission_required('documentation.change_users')
def documentation_auth_group_delete_confirmed(request,group_id):   
    grp = Group.objects.get(id=group_id)
    userx  = grp.user_set.filter()
    for u in userx:
        u.groups.remove(grp)
    
    
    grp.delete()
    
    return HttpResponseRedirect("/documentation/accounts/groups/")

def upload_file(request):
    x=generate_tree(request.user)
    
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
       
        if form.is_valid():
            selected_tags= request.POST.getlist("tag")
            selected_usergroup= request.POST.getlist("usergroup")
            cd = form.cleaned_data
            
            try:
                doc = Document(caption=cd['caption'],document=cd['document'],category=cd['category'],created_by=cd['created_by'],created_on=datetime.datetime.now())
                doc.save()
                doc.tag= Tag.objects.filter(id__in=selected_tags)
                doc.usergroup = Group.objects.filter(id__in=selected_usergroup)
                doc.save()
                pdfcevirmsg= handle_uploaded_file(doc.document.name)
                
                return HttpResponseRedirect("/documentation/categories/"+str(doc.category_id)+"/docs/?msg="+pdfcevirmsg)
            except Exception, e:
                return HttpResponse("Hata : " + str(e))
    else:
        form = DocumentForm()
        
    return render_to_response('documentation/categories.html', {'x':x,'docaddform': form},context_instance=RequestContext(request))

def docs_add(request,cat_id):
    x=generate_tree(request.user)
    docaddform = DocumentForm()
    docaddform['category'].field.initial=cat_id
 
    if not request.user.is_staff:
        docaddform['created_by'].field.queryset=docaddform['created_by'].field.queryset.filter(username=request.user.username)

    return render_to_response('documentation/categories.html', {'x':x,'docaddform': docaddform},context_instance=RequestContext(request))

def docs_edit(request,doc_id):
    x=generate_tree(request.user)
    doc_initial = Document.objects.get(id=doc_id)
    #doc_initial['category']=doc_initial['category_id']
    #doc_initial['created_by']=doc_initial['created_by_id']
    #doc_initial.pop('created_by_id')
    #doc_initial.pop('category_id')
    doceditform = DocumentForm(instance=doc_initial)
    if not request.user.is_staff:
        doceditform['created_by'].field.queryset=doceditform['created_by'].field.queryset.filter(username=request.user.username)   
         
    return render_to_response('documentation/categories.html', {'x':x,'doceditform': doceditform,'doc_current':doc_initial.document.name,'doc_id':doc_id},context_instance=RequestContext(request))

def docs_save(request,doc_id):
    x=generate_tree(request.user)

    doc = get_object_or_404(Document, id=doc_id)
    
    if request.method == 'POST':
        
        form = DocumentForm(data=request.POST, files=request.FILES, instance=doc)
        selected_tags= request.POST.getlist("tag")
        selected_usergroups = request.POST.getlist("usergroup")
        if form.is_valid():

            try:
                            
                form.save()
                doc = get_object_or_404(Document, id=doc_id)
                doc.tag= Tag.objects.filter(id__in=selected_tags)
                doc.usergroup = Group.objects.filter(id__in=selected_usergroups)
                doc.save()
                pdfcevirmsg= handle_uploaded_file(doc.document.name)
                
                xmsg = u"2"
                return HttpResponseRedirect("/documentation/categories/"+str(doc.category_id)+"/docs/?msg="+xmsg)
            
            except Exception, e:
                    return HttpResponse("Hata : " + str(e))
        
        else:
            
            return render_to_response('documentation/categories.html', {'x':x,'doceditform': form,'doc_current':doc.document.name,'doc_id':doc_id},context_instance=RequestContext(request))
            
            
@permission_required('documentation.belge_silebilir')     
def docs_delete(request,doc_id):
    x=generate_tree(request.user)
    doc = Document.objects.filter(id=doc_id)
    
    return render_to_response('documentation/categories.html', {'x':x,'docdeleteform': True,'doc_id':doc_id,'doc':doc,},context_instance=RequestContext(request))

@permission_required('documentation.belge_silebilir')
def docs_delete_confirmed(request,doc_id):
   
    doc = Document.objects.get(id=doc_id)
    cat_id= str(doc.category_id)
    doc.delete()
    
    return HttpResponseRedirect("/documentation/categories/"+cat_id+"/docs/?msg=3")
    
@permission_required('documentation.kategori_duzenleme')
def categories_edit(request,cat_id):
    
    x=generate_tree(request.user)
    #düzenleme formu
    if cat_id:
        cat_initial = Categories.objects.filter(id=cat_id).values()[0]
        parent_id = str(cat_initial['parent_id'])
        form = CategoriesForm(cat_initial)
    
    return render_to_response('documentation/categories.html',{'x':x,'form':form,'cat_id':cat_id,'parent_id':parent_id},context_instance=RequestContext(request))

@permission_required('documentation.kategori_duzenleme')
def categories_save(request,cat_id):
   
    if request.method=="POST":
        
        cat = get_object_or_404(Categories, id=cat_id)
        form = CategoriesForm(request.POST,instance=cat)
        parent_id= cat.parent_id
        if not form.is_valid():
            x=generate_tree(request.user)
            return render_to_response('documentation/categories.html',{'form':form,'x':x,'cat_id':cat_id,'parent_id':parent_id},context_instance=RequestContext(request))
        
        else:
            cd= form.cleaned_data
            cat.sno = cd['sno']
            cat.parent_id= cd['parent_id']  
            cat.aciklama = cd['aciklama']
            #cat.grup= cd['grup']
            
        cat.save()
        return HttpResponseRedirect("/documentation/categories/")
    else:
        return HttpResponse("bullsht ..")

@permission_required('documentation.belge_goruntuleme')
def categories_doclist(request,cat_id):
    x=generate_tree(request.user)
    
    xmsg = request.GET.get('msg')
    
    if xmsg=="1":
        xmsg=u"Dosya Başarıyla Eklendi"
    elif xmsg=="0":
        xmsg=u"Eklendi ancak pdf kopya yaratılamadı .." 
    elif xmsg=="2":
        xmsg=u"Dosya Başarıyla Güncellendi .."
    elif xmsg=="3":
        xmsg=u"Dosya Başarıyla Silindi .."
    elif xmsg=="4":
        xmsg=u"Vazgeçildi .."
    else:
        xmsg=""
        
    cats = get_node_childs(cat_id) #altkategorileridecek 
    cat = Categories.objects.get(id=cat_id)
    docs = Document.objects.filter(category__in=cats).order_by('caption')
    
    if not request.user.is_staff:
        
        if not request.user.has_perm("documentation.belge_tum_liste"):
            
            docs = docs.filter(usergroup__in=request.user.groups.all()).distinct()
            
    
    return render_to_response('documentation/categories.html',{'x':x,'docs':docs,'docsdiv':True,'cat':cat,'msg':xmsg},context_instance=RequestContext(request))


@permission_required('documentation.kategori_olusturma')
def categories_save_as(request):
    
    if request.method=="POST":
        
        form = CategoriesForm(request.POST)
        
        if not form.is_valid():
            x=generate_tree(request.user)
            return render_to_response('documentation/categories.html',{'form':form,'x':x},context_instance=RequestContext(request))
        else:
            cd=form.cleaned_data
            cat = Categories(sno=cd['sno'],aciklama=cd['aciklama'],parent_id=cd['parent_id'].id)
            cat.save()
         
        return HttpResponseRedirect("/documentation/categories/")   

@permission_required('documentation.kategori_olusturma')    
def categories_add(request):
    x=generate_tree(request.user)
    #eklemee formu
    saveasform = CategoriesForm()
    
    return render_to_response('documentation/categories.html',{'x':x,'saveasform':saveasform,},context_instance=RequestContext(request))

@permission_required('documentation.kategori_silme')
def categories_delete(request,cat_id):
    x=generate_tree(request.user)
    cats = Categories.objects.filter(id=cat_id)
    parent_cat = cats[0].parent_id
    
    if parent_cat == 0:
        return HttpResponseRedirect("/documentation/categories/")  
    else:
        bagli_docs = Document.objects.filter(category=cat_id)
        bagli_docs_count= bagli_docs.count()
        
        return render_to_response('documentation/categories.html',{'x':x,'catdeleteform':True,'cats':cats,'bagli_docs':bagli_docs,'bagli_docs_count':bagli_docs_count,'cat_id':cat_id},context_instance=RequestContext(request))


@permission_required('documentation.kategori_silme')
def categories_delete_confirmed(request,cat_id):
    
    xmsg = request.GET.get('docs_confirmed')
    
    cat = Categories.objects.get(id=cat_id)
    aktarilacak_cat_id = cat.parent_id
    
    bagli_catz = Categories.objects.filter(parent_id=cat_id)
    bagli_docs = Document.objects.filter(category=cat_id)
    
    bagli_catz.update(parent_id=aktarilacak_cat_id)
    
    if xmsg == "0":
        bagli_docs.update(category=aktarilacak_cat_id)
        cat.delete()
    else:
        cat.delete()
    
    return HttpResponseRedirect("/documentation/categories/")
    
def categories(request):
    
    x=generate_tree(request.user)
    
    return render_to_response('documentation/categories.html',{'x':x},context_instance=RequestContext(request))

@permission_required('documentation.etiket_olusturma')
def manage_tags(request):
    
    tags = Tag.objects.filter().order_by('name')
    tagform = TagForm()
    return render_to_response('documentation/tags.html',{'tags':tags,'tagform':tagform},context_instance=RequestContext(request))

@permission_required('documentation.etiket_olusturma')
def add_tags(request):
    
    if "name" in request.POST:
        tags = request.POST["name"]
        
        for tag in tags.split():
            Tag.objects.get_or_create(name=tag)[0] 
    
    tags = Tag.objects.filter().order_by('name')
    tagform = TagForm()
    
    return render_to_response('documentation/tags.html',{'tags':tags,'tagform':tagform},context_instance=RequestContext(request))

@permission_required('documentation.etiket_olusturma')
def delete_tags(request):
    selected_tags= []    
    if "tag" in request.POST:
        selected_tags= request.POST.getlist("tag")
        tags = Tag.objects.filter(id__in=selected_tags)
        tags.delete()
    tags = Tag.objects.filter().order_by("name")
    tagform = TagForm()
    return render_to_response('documentation/tags.html',{'tags':tags,'tagform':tagform},context_instance=RequestContext(request))

def search_doc(request):
    x=generate_tree(request.user)
    tags = Tag.objects.filter()
    
    if request.method == "POST":
        searchform = SearchForm(request.POST)
        if not searchform.is_valid():
            
            return render_to_response("documentation/search.html",{'x':x,"searchform":searchform,"tags":tags},context_instance=RequestContext(request))
        else:
            docs = Document.objects.filter(caption__contains = searchform.cleaned_data["text"])
            return render_to_response("documentation/search.html",{'x':x,"searchform":searchform,"docs":docs,"tags":tags},context_instance=RequestContext(request))
    
    
    if request.GET.get('tag'):
        xtag = Tag.objects.filter(name=request.GET.get('tag'))
        docs = Document.objects.filter(tag__in=xtag)
        searchform = SearchForm()
        return render_to_response("documentation/search.html",{'x':x,"searchform":searchform,"docs":docs,"tags":tags},context_instance=RequestContext(request))
        
    searchform = SearchForm()
    return render_to_response("documentation/search.html",{'x':x,"searchform":searchform,"tags":tags},context_instance=RequestContext(request))

def wildcardtrans(xfile):
    #xtr = "ğışİŞĞ"
    #_tr=  "******"
    xfile = xfile.encode('utf-8')
    try:
        #transobj = string.maketrans(xtr, _tr)
        xfile = xfile.replace("ı", "*")
        xfile = xfile.replace("İ", "*")
        xfile = xfile.replace("ş", "*")
        xfile = xfile.replace("Ş", "*")
        xfile = xfile.replace("ğ", "*")
        xfile = xfile.replace("Ğ", "*")
    except Exception, e:
        
        print e.message or  "hata : " + str(e)
        
    return xfile


def handle_uploaded_file(xfile):
    try:
        xfilex= wildcardtrans(xfile) 
       
        #cmd = ['java', '-jar', '/var/www/media/jodconverter-2.2.2/lib/jodconverter-cli-2.2.2.jar','-f pdf',xfilex]
        #i=subprocess.call(cmd) -accept=\"socket,host=127.0.0.1,port=8100;urp;\"
        os.system("soffice -headless -nofirststartwizard")
        time.sleep(1)
        os.system("java -jar /var/www/media/jodconverter-2.2.2/lib/jodconverter-cli-2.2.2.jar -f pdf " + xfilex)
        return u"1"
    except:
        return u"0"



def generate_tree(req_user):
    last_iteration=False
    categories = Categories.objects.all()
    cats = categories.filter(pk__gt=0).order_by('parent_id')
    slist =  []
    
    for c in cats:
        slist.append({'title':unicode(c.id),'parent':get_node_aciklama(c.parent_id)})
    
    source_list = slist#[{'title': 'Project', 'parent':'root'}, {'title': 'Geometry', 'parent':'Geometries'}, {'title': 'Soil', 'parent':'root'}, {'title': 'Geometries', 'parent':'Project'}, {'title': 'Verticals', 'parent':'Project'}, {'title': 'Points', 'parent':'Geometry'}, {'title': 'Layers', 'parent':'Geometry'}, {'title': 'Water', 'parent':'Geometry'}, {'title': 'Soiltypes', 'parent':'Soil'} ] 
    children = {} 
    for d in source_list: 
        children.setdefault(d['parent'], []).append(d['title'])
    
    def signal_last(lst): 
        last2 = None 
        it = iter(lst) 
        try: 
            last = it.next() 
        except StopIteration: 
            last = None 
        for last2 in it: 
            yield False, last 
            last = last2 
        yield True, last 
    
    def get_progeny(title, last_iteration,d=children,c_ack=categories,r_user=req_user):
        
        c_ack=c_ack.filter(id=title)[0]
        if title in d: 
            if d[title]==d:
                dondur = '<ul style="display: none;">'
                for last_iter,child in signal_last(d[title]):
                    if last_iter:
                        last_iteration=True
                        
                    dondur = dondur + get_progeny(child,last_iteration)
                
                return dondur+'</ul>'
                
            else:
                xsay=count_node_and_child_docs(str(c_ack.id))
                if last_iteration:
                    
                    dondur= u"<li class=\"expandable lastExpandable\"><div class=\"hitarea expandable-hitarea lastExpandable-hitarea\"></div>"+c_ack.aciklama+"&nbsp;<small><font color=\"brown\">("+str(xsay)+")</font></small>"+u"<small>"
                   
                    if req_user.has_perm('documentation.kategori_duzenleme'):
                        dondur = dondur + u"&nbsp;<a id=\"inner\" class=\"inner\" href=\"/documentation/categories/"+unicode(title)+u"/duzenle/\">Düzenle</a>"
                    if req_user.has_perm('documentation.belge_goruntuleme'):
                        dondur = dondur + u"&nbsp;<a id=\"inner\" class=\"inner\" href=\"/documentation/categories/"+ str(c_ack.id) +u"/docs/\">Göster</a>"
                        
                    dondur=dondur + u"</small><ul style=\"display: none;\">"
                    
                    last_iteration=False
                
                else:

                    dondur= u"<li class=\"expandable\"><div class=\"hitarea expandable-hitarea\"></div>"+c_ack.aciklama+"&nbsp;<small><font color=\"brown\">("+str(xsay)+")</font></small>"+u"<small>"
                   
                    if req_user.has_perm('documentation.kategori_duzenleme'):
                        dondur = dondur + u"&nbsp;<a id=\"inner\" class=\"inner\" href=\"/documentation/categories/"+unicode(title)+u"/duzenle/\">Düzenle</a>"
                    if req_user.has_perm('documentation.belge_goruntuleme'):
                        dondur = dondur + u"&nbsp;<a id=\"inner\" class=\"inner\" href=\"/documentation/categories/"+ str(c_ack.id) +u"/docs/\">Göster</a>"
                        
                    dondur=dondur + u"</small><ul style=\"display: none;\">"


                for last_iter,child in signal_last(d[title]):
                    if last_iter:
                        last_iteration=True
                    
                    dondur=dondur + get_progeny(child,last_iteration)
                    
                return dondur+ '</ul></li>'
        else: 
            xsay=count_node_and_child_docs(str(c_ack.id))
            if last_iteration:
                last_iteration=False
                htmlcumlesi= u"<li class=\"last\">" + c_ack.aciklama +"&nbsp;<small><font color=\"brown\">("+str(xsay)+")</font></small>"+u"<small>"
                
                if r_user.has_perm('documentation.kategori_duzenleme'):
                    htmlcumlesi= htmlcumlesi + u"&nbsp;<a id=\"inner\" class=\"inner\" href=\"/documentation/categories/"+unicode(title)+u"/duzenle/\">Düzenle</a>"
                if r_user.has_perm('documentation.belge_goruntuleme'):
                    htmlcumlesi= htmlcumlesi + u"&nbsp;<a id=\"inner\" class=\"inner\" href=\"/documentation/categories/"+ str(c_ack.id) +u"/docs/\">Göster</a>"
                
                htmlcumlesi= htmlcumlesi + "</small></li>"
                return htmlcumlesi
                
            else:
                
                htmlcumlesi= u"<li>" + c_ack.aciklama +"&nbsp;<small><font color=\"brown\">("+str(xsay)+")</font></small>"+u"<small>"
                if r_user.has_perm('documentation.kategori_duzenleme'):
                    htmlcumlesi= htmlcumlesi + u"&nbsp;<a id=\"inner\" class=\"inner\" href=\"/documentation/categories/"+unicode(title)+u"/duzenle/\">Düzenle</a>"
                if r_user.has_perm('documentation.belge_goruntuleme'):
                    htmlcumlesi= htmlcumlesi + u"&nbsp;<a id=\"inner\" class=\"inner\" href=\"/documentation/categories/"+ str(c_ack.id) +u"/docs/\">Göster</a>"
                
                htmlcumlesi= htmlcumlesi + "</small></li>"
                return htmlcumlesi
                
            
    source = '<ul class="treeview" id="tree">' 
    result_list = [] 
    
    try:
        for last_iter,child in signal_last(children['root']): 
            
            if last_iter:
                last_iteration=True
                
            source = source + get_progeny(child,last_iteration) 
            result_list.append(get_progeny(child,last_iteration)) 
    except Exception, e:
        #source="Tanımlanmış bir ağaç yapısı yok.."  
        source="Hata : "+ str(e)          
      
    return source

def get_node_childs(parent_id):
    categories = Categories.objects.all()
    cats = categories.filter(pk__gt=0).order_by('parent_id')
    slist =  []
         
    for c in cats:
        slist.append({'title':unicode(c.id),'parent':get_node_aciklama(c.parent_id)})
    
    source_list = slist#[{'title': 'Project', 'parent':'root'}, {'title': 'Geometry', 'parent':'Geometries'}, {'title': 'Soil', 'parent':'root'}, {'title': 'Geometries', 'parent':'Project'}, {'title': 'Verticals', 'parent':'Project'}, {'title': 'Points', 'parent':'Geometry'}, {'title': 'Layers', 'parent':'Geometry'}, {'title': 'Water', 'parent':'Geometry'}, {'title': 'Soiltypes', 'parent':'Soil'} ] 
    children = {} 
    for d in source_list: 
        children.setdefault(d['parent'], []).append(d['title'])
    
    def getchilds(xid,d=children):
        if xid in d:
            return [xid] + [getchilds(child) for child in d[xid]]
        else:
            return [xid]
   
    def flatten(q):
    
        flat_q = []
        for x in q:
            # may have nested tuples or lists
            if type(x) in (list, tuple):
                flat_q.extend(flatten(x))
            else:
                flat_q.append(x)
        return flat_q

    to_flatten_list = getchilds(parent_id)
    
    return flatten(to_flatten_list)

def count_node_and_child_docs(parent_id):
    
    cats = get_node_childs(parent_id)
    return  Document.objects.filter(category__in=cats).count()
    
def get_node_aciklama(xparent_id):
    
    if xparent_id == 0:
        return "root"
    else:
        
        return str(xparent_id)
        #return unicode(Categories.objects.filter(id=xparent_id)[0])
